import React, { useCallback, useLayoutEffect, useRef } from "react";
import echarts, { type ECOption } from "./config";
import { registerMap, type EChartsType } from "echarts";
import { debounce } from "es-toolkit/function";
import ChinaSchema from "@/assets/map/china.json";

interface Props {
  options: ECOption | any;
  renderer?: "canvas" | "svg";
  notMerge?: boolean;
  lazyUpdate?: boolean;
  className?: string | undefined;
}

const EchartsInstance: React.FC<Props> = (props) => {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const echartsRef = useRef<EChartsType | null>(null);

  // 初始化echarts
  const initEcharts = (el: HTMLDivElement | null) => {
    if (!el) return;
    registerMap("china", ChinaSchema as unknown as any);
    // @ts-expect-error EChartsType
    echartsRef.current = echarts.init(el, void 0, {
      renderer: props.renderer || "canvas",
      width: "auto",
      height: "auto"
    });
    setOption(props.options);
    // 监听屏幕缩放，重新绘制 echart 图表
    window.addEventListener("resize", resize);
    resize();
  };

  // 设置echarts
  const setOption = useCallback(
    (option: Props["options"]) => {
      if (!echartsRef.current) return;
      echartsRef.current.setOption(option, props.notMerge, props.lazyUpdate);
    },
    [props.notMerge, props.lazyUpdate]
  );

  // 缩放适配
  const resize = debounce(() => {
    echartsRef.current && echartsRef.current.resize();
  }, 200);

  // 销毁echarts
  const dispose = () => {
    if (!echartsRef.current) return;
    echartsRef.current && echartsRef.current.dispose();
    echartsRef.current = null;
    window.removeEventListener("resize", resize);
  };

  useLayoutEffect(() => {
    initEcharts(containerRef.current);
    return () => {
      dispose();
    };
  }, [props.options]);

  return <div className={props.className} ref={containerRef}></div>;
};

export default React.memo(EchartsInstance);
